package com.cn.bio;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

public class BIOServer {

  static Logger logger = LoggerFactory.getLogger(BIOServer.class);

  public static void main(String[] args) {

    try {

      ServerSocket serverSocket = new ServerSocket(9999);

      while (true) {

        Socket socket = serverSocket.accept();

        // accept 之后每个连接需要开一个线程去维护
        Thread thread = new Thread(new Runnable() {
          @Override
          public void run() {
            InputStream inputStream = null;
            try {
              inputStream = socket.getInputStream();
              InputStreamReader reader = new InputStreamReader(inputStream);
              BufferedReader bufferedReader = new BufferedReader(reader);
              while (bufferedReader.read() != -1) {
                String x = bufferedReader.readLine();
                logger.info(x);
                if (x.endsWith("exit")) break;
              }

              OutputStream outputStream = socket.getOutputStream();
              PrintWriter printWriter = new PrintWriter(outputStream);
              printWriter.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.sss").format(new Date()));
              printWriter.flush();
              printWriter.close();

              logger.info(Thread.currentThread().getName() + " server ...");
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
        });

        thread.start();

      }


    } catch (IOException e) {
      e.printStackTrace();
    }

  }

}
